package org.essilab.analyzer.wikitionary;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.essilab.analyzer.Configuration.Config;
import org.essilab.analyzer.analyzer.*;
import org.essilab.analyzer.util.Language;
import org.xml.sax.SAXException;

/**
 * This class is used to init a Term object from a Page object.
 *
 * @author Mohamed-Amine Chouchene, Ahcène Idinarere, Vincent Nock, Alain
 * Janin-Manificat
 */
public class WikiArticle implements IArticle {
	private static Integer count = 0;
	private static Pattern _p = Pattern.compile("== \\{\\{=([a-zA-Z]{2,})=\\}\\} ==", Pattern.CASE_INSENSITIVE| Pattern.MULTILINE);
	private static Matcher _m = null;
	private FileWriter _writer = null;

	@Override
	public void process(Page page) throws SAXException {
		if (null != page.getText() && !page.getText().trim().isEmpty() && !page.getTitle().contains("Aide:")) {

			if (isFrench(page.getText())) {
				Term term = new Term();
				term.setTitle(page.getTitle());
				//term.setNormalizedTitle(Normalizer.normalizer(page.getTitle()).toLowerCase());
				term.setCreatedAt(page.getTimeStamp());
				term.setLang(Language.FRENCH);
				ITemplate template = new TemplateWiki();
				template.process(term, page.getText());
				 Files file = new Files();
				 file.saveTerm(term);
				if(Config.get("usesql").equals("true")){
					saveSql(generateSql(term.getTitle(),generateDate(term.getCreatedAt())));
				}
			}
		}
	}

	/**
	 * Tell whether or not a text is French.
	 * @param text  String - text to analyse.
	 * @return      boolean - True if the text is in French, false otherwise.
	 */
	private boolean isFrench(String text) {
		_m = _p.matcher(text);
		while (_m.find()) {
			if (_m.group(1).equals(Language.FRENCH)) {
				return true;
			}
		}
		return false;
	}
	/**
	 * 
	 * @param title
	 * @param date
	 * @return
	 */
	private String generateSql(String title,String date){
		return "INSERT INTO terms(idterms,title, date, language) VALUES ("+(++count)+",'"+title+"',"+(null!=date?("'"+date+"'"):"")+",'fr');\n\n";
	}
	/**
	 * 
	 * @param date
	 * @return
	 */
	private String generateDate(String date){
		if(null!=date)
			return date.split("T")[0];
		return null;
	}
	/**
	 * 
	 * @param sql
	 */
	private void saveSql(String sql){
		String filename =null!=Config.get("sqldump")?Config.get("sqldump"):"dump.sql";
		File f = new File(filename);
		if(!f.exists())
			try {
				f.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		try {
			this._writer = new FileWriter(f, true);
			this._writer.write(sql);
			this._writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
